package com.adinnet.admin.course.controller;

import com.adinnet.admin.common.service.CommonService;
import com.adinnet.admin.course.model.Course;
import com.adinnet.admin.course.model.vo.CourseResp;
import com.adinnet.admin.course.service.CourseService;
import com.adinnet.admin.sentence.mapper.SentenceMapper;
import com.adinnet.admin.sentence.model.Sentence;
import com.adinnet.admin.sentence.service.SentenceService;
import com.adinnet.admin.video.mapper.VideoMapper;
import com.adinnet.admin.video.model.Video;
import com.adinnet.admin.video.service.VideoService;
import com.adinnet.admin.word.mapper.WordMapper;
import com.adinnet.admin.word.model.Word;
import com.adinnet.admin.word.service.WordService;
import com.adinnet.core.JsonResult;
import com.adinnet.core.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 课程表 前端控制器
 * </p>
 *
 * @author zYshuai
 * @since 2020-12-11
 */
@Controller
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private CourseService courseService;
    @Autowired
    private VideoService videoService;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private WordService wordService;
    @Autowired
    private WordMapper wordMapper;
    @Autowired
    private SentenceService sentenceService;
    @Autowired
    private SentenceMapper sentenceMapper;
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    private CommonService commonService;

    

    @RequestMapping()
    public String course(Model model) {
        return "course/course.html";
    }
    @RequestMapping("/courseDetail")
    public String courseDetail(Model model,String id) {
        model.addAttribute("courseId",id);
        return "course/courseDetail.html";
    }

    /**
     * @Description 1.视频/2.音频 3.重点词汇 4.跟读训练 分页列表查询
     * @author dmm 
     * @param type 类型  1.视频/2.音频 3.重点词汇 4.跟读训练
     * @param keywords 查询关键字
     * @param courseId 课程id
     * @createTime: 2020/12/18 10:45
    */
    @ResponseBody
    @RequestMapping("/getListPage")
    public Object getListPage(Integer page, Integer limit,Integer type,String keywords,String courseId) {
        if (page == null || limit == null) { page = 1; limit = 10; }
        // 1.视频/2.音频
        if(type.intValue() == 1 || type.intValue() == 2 ){
            QueryWrapper<Video> qw = new QueryWrapper<>();
            qw.eq("type", type.intValue() == 1 ? "VOICE_VIDEO" : "VOICE" );
            if(StringUtils.isNotBlank(keywords))qw.apply(" CONCAT_WS(',',id,serial_number,video_name) LIKE CONCAT('%',TRIM({0}),'%')", keywords);
            IPage<Video> iPage = videoMapper.selectPage(new Page<>(page, limit), qw.eq("deleted", 0).eq("course_id",courseId).orderByAsc("serial_number").orderByDesc("updated_date"));
            return new PageResult<>(iPage.getRecords(), iPage.getTotal());
        }
        // 2.重点词汇
        if(type.intValue() == 3){
            QueryWrapper<Word> qw = new QueryWrapper<>();
            if(StringUtils.isNotBlank(keywords))qw.apply(" CONCAT_WS(',',id,serial_number,word_name) LIKE CONCAT('%',TRIM({0}),'%')", keywords);
            IPage<Word> iPage = wordMapper.selectPage(new Page<>(page, limit), qw.eq("deleted", 0).eq("course_id",courseId).orderByAsc("serial_number").orderByDesc("updated_date"));
            return new PageResult<>(iPage.getRecords(), iPage.getTotal());
        }
        // 3.跟读训练
        if(type.intValue() == 4){
            QueryWrapper<Sentence> qw = new QueryWrapper<>();
            if(StringUtils.isNotBlank(keywords))qw.apply(" CONCAT_WS(',',id,serial_number,sentence_name) LIKE CONCAT('%',TRIM({0}),'%')", keywords);
            IPage<Sentence> iPage = sentenceMapper.selectPage(new Page<>(page, limit), qw.eq("deleted", 0).eq("course_id",courseId).orderByAsc("serial_number").orderByDesc("updated_date"));
            return new PageResult<>(iPage.getRecords(), iPage.getTotal());
        }
        return null;
    }
    
    /**
     * @Description 批量逻辑删除 1.视频/音频 2.重点词汇 3.跟读训练
     * @author dmm 
     * @param type 类型  1.视频/音频 2.重点词汇 3.跟读训练 
     * @param ids 对应类型的主键id 
     * @createTime: 2020/12/19 11:15
    */
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    @RequestMapping("/delCourseDetail")
    public JsonResult delCourseDetail(String type,String ids){
        commonService.saveOperation(request,"课程管理-删除-"+(" 视频 音频 重点词汇 跟读训练".split(" ")[Integer.valueOf(type)]));
        if("1".equals(type) || "2".equals(type) ){
            UpdateWrapper<Video> uw = new UpdateWrapper<>();
            uw.set("deleted",1).apply("FIND_IN_SET(id,{0})",ids);
            if(videoService.update(uw)) return JsonResult.ok("操作成功");
        }
        if("3".equals(type)){
            UpdateWrapper<Word> uw = new UpdateWrapper<>();
            uw.set("deleted",1).apply("FIND_IN_SET(id,{0})",ids);
            if(wordService.update(uw)) return JsonResult.ok("操作成功");
        }
        if("4".equals(type)){
            UpdateWrapper<Sentence> uw = new UpdateWrapper<>();
            uw.set("deleted",1).apply("FIND_IN_SET(id,{0})",ids);
            if(sentenceService.update(uw)) return JsonResult.ok("操作成功");
        }
        return JsonResult.error("操作失败");
    }
    
    /**
     * @Description 新增/修改 1.视频/音频 2.重点词汇 3.跟读训练
     * @author dmm 
     * @param jsonStr 对象  1.视频/音频 2.重点词汇 3.跟读训练 
     * @createTime: 2020/12/21 13:55
    */
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    @RequestMapping("/crudCourseDetail")
    public JsonResult crudCourseDetail(String jsonStr){
        JSONObject json = JSONObject.parseObject(jsonStr);

        int type = json.getInteger("type");
        String flag = json.getString("flag");
        commonService.saveOperation(request,String.format("课程管理-%s-%s","add".equals("flag")?"新增":"修改"," 视频 音频 重点词汇 跟读训练".split(" ")[type]));
        if(1==type || 2 == type){
            Video entity = json.toJavaObject(Video.class);
            entity.setType( 1 == type ? "VOICE_VIDEO" : "VOICE");
            if("add".equals(flag))videoService.save(entity);
            else videoService.updateById(entity);
        }
        if(3==type){
            Word entity = json.toJavaObject(Word.class);
            if("add".equals(flag))wordService.save(entity);
            else wordService.updateById(entity);
        }
        if(4==type){
            Sentence entity = json.toJavaObject(Sentence.class);
            if("add".equals(flag))sentenceService.save(entity);
            else sentenceService.updateById(entity);
        }
        return JsonResult.ok("操作成功");
    }

    /**
     * 课程列表
     **/
    @ResponseBody
    @RequestMapping("/list")
    public PageResult<CourseResp> list(String keyword,Integer page, Integer limit) {
        if (page == null || limit == null) {
            page = 1;
            limit = 10;
        }
        return courseService.courseList(keyword,page,limit);
    }

    /**
     * 添加课程
     */
    @RequestMapping("/add")
    @ResponseBody
    public JsonResult add(Course course) {
        if (courseService.save(course)) {
            commonService.saveOperation(request,"新增课程，课程名称："+course.getCourseName());
            return JsonResult.ok("添加成功");
        }
        return JsonResult.error("添加失败");
    }

    /**
     * 修改课程
     */
    @RequestMapping("/update")
    @ResponseBody
    public JsonResult update(Course course) {
        if (courseService.updateById(course)) {
            commonService.saveOperation(request,"修改课程，课程ID："+course.getId());
            return JsonResult.ok("修改成功");
        }
        return JsonResult.error("修改失败");
    }

    /**
     * 删除课程
     */
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Integer courseId) {
        commonService.saveOperation(request,"删除课程，课程ID："+courseId);
        return courseService.delete(courseId);
    }

}
